using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;
using UniversalAdmin.Api.Filters;

[ApiController]
[Route("api/users")]
[Authorize]
public class UsersController : ControllerBase
{
    private readonly IAppUserServices _userService;
    public UsersController(IAppUserServices userService) { _userService = userService; }

    // 分页+搜索
    [HttpGet]
    [RequirePermission("user.view")] // 需要查看用户权限
    public async Task<ApiResult> Get([FromQuery] int? page = null, [FromQuery] int? size = null, [FromQuery] string? search = null)
    {
        if (page.HasValue && size.HasValue)
        {
            var result = await _userService.GetPagedAsync(new PagedQuery { Page = page.Value, Size = size.Value, Search = search });
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
        else
        {
            var result = await _userService.GetAllAsync(search);
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
    }

    // 获取单个用户
    [HttpGet("{id}")]
    [RequirePermission("user.view")] // 需要查看用户权限
    public async Task<ApiResult> GetById(Guid id)
    {
        try
        {
            var result = await _userService.GetByIdAsync(id);
            if (result.Code != 200)
            {
                return ApiResult.Failed(result.Code, result.Message);
            }

            var user = result.Data;

            // 获取用户角色
            var rolesResult = await _userService.GetUserRolesDetailAsync(id);
            var roles = rolesResult.Select(r => r.RoleName).ToList();

            var userInfo = new
            {
                userId = user.Id,
                userName = user.UserName,
                email = user.Email,
                phone = user.Phone,
                avatar = user.Avatar,
                isActive = user.IsActive,
                roles = roles
            };

            return ApiResult.Success("获取用户信息成功", userInfo);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户信息时发生错误: {ex.Message}");
        }
    }

    // 通过用户ID获取头像信息
    [HttpGet("{id}/avatar-info")]
    [RequirePermission("user.view")] // 需要查看用户权限
    public async Task<ApiResult> GetUserAvatarInfo(Guid id)
    {
        try
        {
            var result = await _userService.GetByIdAsync(id);
            if (result.Code != 200)
            {
                return ApiResult.Failed(result.Code, result.Message);
            }

            var user = result.Data;
            return ApiResult.Success("获取头像信息成功", new { 
                userId = user.Id,
                userName = user.UserName,
                avatar = user.Avatar
            });
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取头像信息时发生错误: {ex.Message}");
        }
    }

    // 获取用户角色（返回详细信息）
    [HttpGet("{id}/roles")]
    [RequirePermission("user.view")] // 需要查看用户权限
    public async Task<ApiResult<IEnumerable<RoleDto>>> GetUserRoles(Guid id)
        => ApiResult<IEnumerable<RoleDto>>.Success((int)ApiStatusCode.SUCCESS, "操作成功", await _userService.GetUserRolesDetailAsync(id));

    // 创建用户
    [HttpPost]
    [RequirePermission("user.create")] // 需要创建用户权限
    public async Task<ApiResult> Create([FromBody] CreateUserDto dto)
    {
        var allUsersResult = await _userService.GetAllAsync();
        if (allUsersResult.Data != null && allUsersResult.Data.Any(u => u.UserName.Trim().ToLower() == dto.Username.Trim().ToLower()))
        {
            return ApiResult.Failed((int)ApiStatusCode.CONFLICT, "用户名已存在");
        }
        return await _userService.CreateAsync(dto);
    }

    // 更新用户
    [HttpPut("{id}")]
    [RequirePermission("user.edit")] // 需要编辑用户权限
    public async Task<ApiResult> Update(Guid id, [FromBody] UpdateUserDto dto)
    {
        // 获取当前用户ID
        var currentUserIdClaim = User.FindFirst("UserId");
        Guid? currentUserId = null;
        if (currentUserIdClaim != null && Guid.TryParse(currentUserIdClaim.Value, out var userId))
        {
            currentUserId = userId;
        }

        // 检查当前用户是否有管理员权限
        bool isAdmin = false;
        if (currentUserId.HasValue)
        {
            isAdmin = await _userService.HasPermissionAsync(currentUserId.Value, "user.manage");
        }

        // 如果不是管理员，只能修改自己的信息
        if (!isAdmin && currentUserId.HasValue && id != currentUserId.Value)
        {
            return ApiResult.Failed((int)ApiStatusCode.FORBIDDEN, "只能修改自己的信息");
        }

        var result = await _userService.UpdateAsync(id, dto, currentUserId);

        // 如果更新成功，返回最新的用户信息
        if (result.Code == 200)
        {
            var userResult = await _userService.GetByIdAsync(id);
            if (userResult.Code == 200)
            {
                var user = userResult.Data;

                // 获取用户角色
                var rolesResult = await _userService.GetUserRolesDetailAsync(id);
                var roles = rolesResult.Select(r => r.RoleName).ToList();

                var userInfo = new
                {
                    userId = user.Id,
                    userName = user.UserName,
                    email = user.Email,
                    phone = user.Phone,
                    avatar = user.Avatar,
                    isActive = user.IsActive,
                    roles = roles
                };

                return ApiResult.Success("更新成功", userInfo);
            }
        }
        return result;
    }

    // 删除用户
    [HttpDelete("{id}")]
    [RequirePermission("user.delete")] // 需要删除用户权限
    public async Task<ApiResult> Delete(Guid id)
    {
        // 获取当前用户ID
        var currentUserIdClaim = User.FindFirst("UserId");
        Guid? currentUserId = null;
        if (currentUserIdClaim != null && Guid.TryParse(currentUserIdClaim.Value, out var userId))
        {
            currentUserId = userId;
        }
        
        return await _userService.DeleteAsync(id, currentUserId);
    }

    // 上传头像
    [HttpPost("{id}/avatar")]
    [RequirePermission("user.avatar")] // 需要头像上传权限
    public async Task<ApiResult> UploadAvatar(Guid id, [FromForm] IFormFile file)
    {
        // 获取当前用户ID
        var currentUserIdClaim = User.FindFirst("UserId");
        Guid? currentUserId = null;
        if (currentUserIdClaim != null && Guid.TryParse(currentUserIdClaim.Value, out var userId))
        {
            currentUserId = userId;
        }
        
        // 检查当前用户是否有管理员权限
        bool isAdmin = false;
        if (currentUserId.HasValue)
        {
            isAdmin = await _userService.HasPermissionAsync(currentUserId.Value, "user.manage");
        }
        
        // 如果不是管理员，只能修改自己的头像
        if (!isAdmin && currentUserId.HasValue && id != currentUserId.Value)
        {
            return ApiResult.Failed((int)ApiStatusCode.FORBIDDEN, "只能修改自己的头像");
        }
        
        return await _userService.UploadAvatarAsync(id, file, currentUserId);
    }

    // 获取头像文件
    [HttpGet("avatar/{fileName}")]
    [AllowAnonymous]
    public async Task<IActionResult> GetAvatarFile(string fileName)
    {
        try
        {
            // 安全检查：防止路径遍历攻击
            if (string.IsNullOrEmpty(fileName) || fileName.Contains("..") || fileName.Contains("/") || fileName.Contains("\\"))
            {
                return BadRequest("无效的文件名");
            }

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "avatars", fileName);
            
            // 检查文件是否存在
            if (!System.IO.File.Exists(filePath))
            {
                // 如果文件不存在，返回默认头像
                var defaultAvatarPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "avatars", "default-avatar.png");
                if (System.IO.File.Exists(defaultAvatarPath))
                {
                    var defaultContentType = GetContentType(Path.GetExtension(defaultAvatarPath));
                    var defaultFileBytes = await System.IO.File.ReadAllBytesAsync(defaultAvatarPath);
                    return File(defaultFileBytes, defaultContentType, "default-avatar.png");
                }
                
                return NotFound("头像文件不存在");
            }

            var contentType = GetContentType(Path.GetExtension(filePath));
            var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
            return File(fileBytes, contentType, fileName);
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"获取头像文件时发生错误: {ex.Message}");
        }
    }

    // 获取文件MIME类型
    private string GetContentType(string extension)
    {
        return extension.ToLowerInvariant() switch
        {
            ".jpg" or ".jpeg" => "image/jpeg",
            ".png" => "image/png",
            ".gif" => "image/gif",
            ".bmp" => "image/bmp",
            _ => "application/octet-stream"
        };
    }

    // 修改密码
    [HttpPost("{id}/ChangePassword")]
    [RequirePermission("user.edit")] // 需要编辑用户权限
    public async Task<ApiResult> ChangePassword(Guid id, [FromBody] ChangePasswordDto dto)
    {
        // 获取当前用户ID
        var currentUserIdClaim = User.FindFirst("UserId");
        Guid? currentUserId = null;
        if (currentUserIdClaim != null && Guid.TryParse(currentUserIdClaim.Value, out var userId))
        {
            currentUserId = userId;
        }

        // 检查当前用户是否有管理员权限
        bool isAdmin = false;
        if (currentUserId.HasValue)
        {
            isAdmin = await _userService.HasPermissionAsync(currentUserId.Value, "user.manage");
        }

        // 如果不是管理员，只能修改自己的密码
        if (!isAdmin && currentUserId.HasValue && id != currentUserId.Value)
        {
            return ApiResult.Failed((int)ApiStatusCode.FORBIDDEN, "只能修改自己的密码");
        }

        return await _userService.ChangePasswordAsync(id, dto, currentUserId);
    }

    // 启用用户
    [HttpPost("{id}/enable")]
    [RequirePermission("user.manage")] // 需要管理用户权限
    public async Task<ApiResult> EnableAsync(Guid id)
    {
        return await _userService.EnableAsync(id);
    }

    // 禁用用户
    [HttpPost("{id}/disable")]
    [RequirePermission("user.manage")] // 需要管理用户权限
    public async Task<ApiResult> DisableAsync(Guid id)
    {
        // 获取当前用户ID
        var currentUserIdClaim = User.FindFirst("UserId");
        Guid? currentUserId = null;
        if (currentUserIdClaim != null && Guid.TryParse(currentUserIdClaim.Value, out var userId))
        {
            currentUserId = userId;
        }
        
        return await _userService.DisableAsync(id, currentUserId);
    }

    // 分配角色
    [HttpPost("{id}/roles")]
    [RequirePermission("user.manage")] // 需要管理用户权限
    public async Task<ApiResult> AssignRoles(Guid id, [FromBody] AssignUserRolesDto dto)
    {
        return await _userService.AssignRolesAsync(id, dto.RoleIds);
    }

    // 测试IP地址获取
    [HttpGet("test-ip")]
    [AllowAnonymous]
    public IActionResult TestIp()
    {
        var ip = GetClientIpAddress(Request.HttpContext);
        return Ok(new { 
            clientIp = ip,
            forwardedFor = Request.Headers["X-Forwarded-For"].ToString(),
            realIp = Request.Headers["X-Real-IP"].ToString(),
            clientIpHeader = Request.Headers["X-Client-IP"].ToString(),
            cfConnectingIp = Request.Headers["CF-Connecting-IP"].ToString(),
            remoteIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
        });
    }

    // 获取真实客户端IP地址
    private string GetClientIpAddress(HttpContext context)
    {
        // 尝试从各种头部获取真实IP
        var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault()?.Split(',')[0]?.Trim();
        if (!string.IsNullOrEmpty(ip) && ip != "unknown")
            return ip;

        ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
        if (!string.IsNullOrEmpty(ip))
            return ip;

        ip = context.Request.Headers["X-Client-IP"].FirstOrDefault();
        if (!string.IsNullOrEmpty(ip))
            return ip;

        ip = context.Request.Headers["CF-Connecting-IP"].FirstOrDefault();
        if (!string.IsNullOrEmpty(ip))
            return ip;

        // 获取连接IP，优先IPv4
        var remoteIp = context.Connection.RemoteIpAddress;
        if (remoteIp != null)
        {
            // 如果是IPv6映射的IPv4地址，转换为IPv4
            if (remoteIp.IsIPv4MappedToIPv6)
            {
                return remoteIp.MapToIPv4().ToString();
            }
            // 如果是IPv6本地回环，返回IPv4的localhost
            else if (remoteIp.ToString() == "::1")
            {
                return "127.0.0.1";
            }
            else
            {
                return remoteIp.ToString();
            }
        }
        
        return "unknown";
    }
} 